package top.ywlog.permission.controller;

import lombok.extern.slf4j.Slf4j;
import org.springframework.stereotype.Controller;
import org.springframework.validation.annotation.Validated;
import org.springframework.web.bind.annotation.*;
import top.ywlog.permission.common.request.LoginParam;
import top.ywlog.permission.common.response.Result;
import top.ywlog.permission.common.response.ResultCode;
import top.ywlog.permission.dao.SysUserMapper;
import top.ywlog.permission.model.Mail;
import top.ywlog.permission.model.SysUser;
import top.ywlog.permission.service.MailService;
import top.ywlog.permission.util.MD5Utils;

import javax.annotation.Resource;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpSession;
import java.util.Objects;

/**
 * @author: Durian
 * @date: 2020/10/21 21:19
 * @description:
 */
@Slf4j
@Controller
public class MainController
{
    /** 用户信息的 session id */
    private static final String SESSION_USERNAME = "user";

    @Resource
    private SysUserMapper sysUserMapper;
    @Resource
    private MailService mailService;

    @PostMapping("/login")
    @ResponseBody
    public Result login(@RequestBody @Validated LoginParam param, HttpServletRequest request)
    {
        SysUser user = sysUserMapper.findByKeyword(param.getUsername());
        if (user == null)
        {
            return Result.fail(ResultCode.USER_NOTFOUND);
        }
        if (Objects.equals(MD5Utils.encrypt(param.getPassword()), user.getPassword()))
        {
            if (user.getStatus() == 0)
            {
                return Result.fail(ResultCode.USER_FROZEN);
            }
            // 登录成功
            request.getSession().setAttribute(SESSION_USERNAME, user);
            log.info("用户 {} 登录成功", user.getUsername());
            return Result.success();
        }

        return Result.fail(ResultCode.USER_PASSWORD_ERROR);
    }

    @GetMapping("/logout")
    @ResponseBody
    public Result logout(HttpServletRequest request)
    {
        HttpSession session = request.getSession(false);
        if (session != null && session.getAttribute(SESSION_USERNAME) != null)
        {
            SysUser user = (SysUser) session.getAttribute(SESSION_USERNAME);
            // 注销session
            request.getSession().invalidate();
            log.info("用户 {} 注销登录", user.getUsername());
        }
        return Result.success();
    }
}
